package com.tjp.eight.utils;

import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.widget.TextView;

import com.tjp.eight.RxBus;
import com.tjp.eight.WApplication;
import com.tjp.eight.ui.fragment.homepage.HomePageAdapter;
import com.tjp.eight.ui.fragment.personsetting.PicEvent;
import com.tjp.eight.views.emoj.EmojiUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by Administrator on 2017/2/27.
 */

public class AppUtils {
    private final static int[] dayArr = new int[]{20, 19, 21, 20, 21, 22, 23, 23, 23, 24, 23, 22};
    private final static String[] constellationArr = new String[]{"摩羯座", "水瓶座", "双鱼座", "白羊座", "金牛座", "双子座", "巨蟹座", "狮子座", "处女座", "天秤座", "天蝎座", "射手座", "摩羯座"};


    public static String getConstellation(int month, int day) {
        return day < dayArr[month - 1] ? constellationArr[month - 1] : constellationArr[month];
    }

    public static void setTextViewColor(TextView textViewColor, String colorStr) {
        int color = Color.parseColor(colorStr);
        textViewColor.setTextColor(color);
    }

    public static RequestBody getRequestBody(String json) {
        return RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
    }

    public static boolean check(FragmentActivity context) {
        boolean is = false;
        if (Build.VERSION.SDK_INT >= 23) {
            String[] mPermissionList = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CALL_PHONE,
                    Manifest.permission.READ_LOGS, Manifest.permission.READ_PHONE_STATE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.SET_DEBUG_APP,
                    Manifest.permission.SYSTEM_ALERT_WINDOW, Manifest.permission.GET_ACCOUNTS,
                    Manifest.permission.WRITE_APN_SETTINGS};

            for (String m : mPermissionList) {
                if (ActivityCompat.checkSelfPermission(context, m) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(context, new String[]{m}, 1222);
                    is = true;
                }
            }
        }
        return is;
    }

    public static ArrayList<String> getNames(String detail) {
        ArrayList<String> names = new ArrayList<>();
//        String name = "[^\\{8m key=\"\\s*\" uid=\"\\d*\"\\}]\\S*(?=\\{/8m\\})";
        String name = "\\{8m key=\"name\" uid=\"\\d*\"\\}(\\S*)(?=\\{/8m\\})";
        Pattern patternname = Pattern.compile(name);
        Matcher matchern = patternname.matcher(detail);
        while (matchern.find()) {
            names.add(matchern.group());
        }
        ArrayList<String> temp = new ArrayList<>();
        for (String s : names) {
            int index = s.indexOf('}') + 1;
            String sub = s.substring(index, s.length());
            temp.add(sub);
        }
        return temp;
    }

    public static ArrayList<String> getUids(String detail) {
        ArrayList<String> names = new ArrayList<>();
        String uid = "(?!(uid=))(\"\\d*\")";
        Pattern patternname = Pattern.compile(uid);
        Matcher matchern = patternname.matcher(detail);
        while (matchern.find()) {
            names.add(matchern.group());
        }
        return names;
    }

    public static String[] getSplit(String detail) {
        String reg = "\\{8m key=\"name\" uid=\"\\d*\"\\}\\S*\\{/8m\\}";
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(detail);
        String temp = "";
        while (matcher.find()) {
            temp = matcher.replaceAll("AA_AA_AAAA_AA_AA");
        }
        return temp.split("AA_AA_AAAA_AA_AA");
    }

    public static String[] getUrl(String[] urls) {
        String reg = "(.*?(jpg|jpeg|gif|png))";

        Pattern pattern = Pattern.compile(reg);

        ArrayList<String> temp = new ArrayList<>();
        for (String url : urls) {
            Matcher matcher = pattern.matcher(url);
            while (matcher.find()) {
                temp.add(url);
            }
        }
        String[] result = new String[temp.size()];
        for (int i = 0; i < temp.size(); i++) {
            result[i] = temp.get(i);
        }

        return result;
    }

    public static String[] getUrls(String[] urls) {


        ArrayList<String> temp = new ArrayList<>();
        for (String url : urls) {
            if (!url.startsWith("data:image") && !StringUtils.isNullOrEmpty(url)) {
                temp.add(url);
            }
        }
        String[] result = new String[temp.size()];
        for (int i = 0; i < temp.size(); i++) {
            result[i] = temp.get(i);
        }

        return result;
    }

    public static String getDetail(Object what, Object what1, String[] split, ArrayList<String> names, TextView textView, Context context) {
        String detail = "";
        if (names.size() > 1) {
            detail = split[0] + names.get(0) + split[1] + names.get(1);//+ split[split.length - 1];
            SpannableString spannableString = new SpannableString(detail);
            spannableString.setSpan(what1, split[0].length(), names.get(0).length() + split[0].length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            Log.e("names", "" + names.toString());
            spannableString.setSpan(what, names.get(0).length() + split[0].length() + split[1].length()
                    , names.get(0).length() + split[0].length() + split[1].length() + names.get(1).length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            textView.setText(spannableString);
            try {
                new EmojiUtil().handlerEmojiTextAppend(textView, split[split.length - 1], context);
            } catch (IOException e) {
                e.printStackTrace();
            }
            textView.setMovementMethod(LinkMovementMethod.getInstance());
        } else {
            detail = split[0] + names.get(0);//+ split[split.length - 1];
            SpannableString spannableString = new SpannableString(detail);
            spannableString.setSpan(what, split[0].length(), names.get(0).length() + split[0].length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            textView.setText(spannableString);
            try {
                new EmojiUtil().handlerEmojiTextAppend(textView, split[split.length - 1], context);
            } catch (IOException e) {
                e.printStackTrace();
            }
            textView.setMovementMethod(LinkMovementMethod.getInstance());
        }

        return detail;
    }

    public static void refreshMe() {
        RxBus.getInstance().post(PicEvent.class);
    }

    public static void goToMarket(Context context, String packageName) {
        Uri uri = Uri.parse("market://details?id=" + packageName);
        Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
        try {
            goToMarket.setClassName("com.tencent.android.qqdownloader", "com.tencent.pangu.link.LinkProxyActivity");
            context.startActivity(goToMarket);
        } catch (ActivityNotFoundException e) {
            ToatUtils.toastNoInstall(context, "未检测到应用宝");
            e.printStackTrace();
        }
    }

    final static Pattern pattern = Pattern.compile("\\S*[?]\\S*");

    /**
     * 获取链接的后缀名
     *
     * @return
     */
    public static String parseSuffix(String url) {
        if (StringUtils.isNullOrEmpty(url))
            return "";
        Matcher matcher = pattern.matcher(url);

        String[] spUrl = url.toString().split("/");
        int len = spUrl.length;
        String endUrl = spUrl[len - 1];

        if (matcher.find()) {
            String[] spEndUrl = endUrl.split("\\?");
            String[] sp = spEndUrl[0].split("\\.");
            return sp[sp.length - 1];
        }
        return endUrl.split("\\.")[1];
    }
}
